import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_utils/screen.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';

import '../../hj_model/acg/comic_chapters_model.dart';
import '../../tools_base/loading/l_error_widget.dart';
import '../../tools_base/loading/loading_center_widget.dart';
import 'text_novel_read_logic.dart';
import 'widget/acg_source_manager.dart';

//文字小说阅读页
class TextNovelReadPage extends StatefulWidget {
  static const routeName = '/textnovel/read';
  final ACGSourceManager manager;
  const TextNovelReadPage({super.key, required this.manager});

  @override
  State<TextNovelReadPage> createState() => _TextNovelReadPageState();
}

class _TextNovelReadPageState extends State<TextNovelReadPage> {
  late TextNovelReadLogic logic;

  @override
  void initState() {
    super.initState();
    logic = Get.put(TextNovelReadLogic(widget.manager));
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<TextNovelReadLogic>(
      builder: (_) => Scaffold(
        backgroundColor: _.isDark ? Color(0xff141414) : Colors.white,
        body: () {
          if (_.detailInfo == null) return LoadingCenterWidget();
          if (_.detailInfo?.id == null) return CErrorWidget(retryOnTap: () => _.loadData());
          return Builder(
            builder: (context) => Stack(
              fit: StackFit.expand,
              children: [
                _buildContent(),
                _buildHeader(context),
                _buildFooter(),
              ],
            ),
          );
        }(),
        endDrawer: _buildEndDrawer(),
      ),
    );
  }

  _buildContent() {
    return InkWell(
      onTap: () => logic.onShowMenuAction(),
      child: Container(
        color: logic.isDark ? Color(0xff1E1E1E) : Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
        child: SafeArea(
            bottom: false,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '${logic.mediaInfo?.title ?? ''}/${logic.detailInfo?.name ?? ''}',
                  style: TextStyle(
                    fontSize: 16,
                    color: Color(0xff525252),
                    fontWeight: FontWeight.w400,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                16.sizeBoxH,
                Expanded(
                  child: SingleChildScrollView(
                    controller: logic.scrollCtr,
                    child: Column(
                      children: [
                        Text(
                          logic.detailInfo?.text ?? '',
                          style: TextStyle(
                            fontSize: 16,
                            color: logic.isDark ? Colors.white.withOpacity(.9) : Colors.black.withOpacity(.9),
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                        60.sizeBoxH,
                      ],
                    ),
                  ),
                )
              ],
            )),
      ),
    );
  }

  //header
  _buildHeader(BuildContext ctx) {
    return AnimatedPositioned(
      duration: Duration(milliseconds: logic.durationTime),
      top: logic.showMenu ? 0 : -(44 + screen.paddingTop),
      left: 0,
      right: 0,
      child: Container(
        alignment: Alignment.bottomCenter,
        color: logic.isDark ? Colors.black : Colors.white,
        padding: const EdgeInsets.only(left: 16, right: 16),
        child: SizedBox(
            height: (44 + screen.paddingTop),
            child: Column(
              children: [
                (screen.paddingTop + 5).sizeBoxH,
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    InkWell(
                      onTap: () => Get.back(),
                      child: Icon(
                        Icons.arrow_back_ios,
                        size: 24,
                        color: logic.isDark ? Colors.white : Colors.black,
                      ),
                    ),
                    Expanded(
                      child: Text(
                        logic.detailInfo?.name ?? '',
                        style: TextStyle(
                          fontSize: 18,
                          color: logic.isDark ? Colors.white : Colors.black,
                          fontWeight: FontWeight.w600,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    InkWell(
                      onTap: () => logic.changeDarkStyle(),
                      child: Padding(
                        padding: EdgeInsets.symmetric(horizontal: 7),
                        child: Image.asset(
                          logic.isDark ? 'text_sun.png'.acgImgPath : 'text_moon.png'.acgImgPath,
                          width: 24,
                        ),
                      ),
                    ),
                    InkWell(
                      onTap: () => Scaffold.of(ctx).openEndDrawer(),
                      child: Padding(
                        padding: EdgeInsets.symmetric(horizontal: 7),
                        child: Image.asset(
                          'text_play_menu.png'.acgImgPath,
                          width: 24,
                          color: logic.isDark ? Colors.white : Colors.black,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            )),
      ),
    );
  }

  _buildFooter() {
    return AnimatedPositioned(
      duration: Duration(milliseconds: logic.durationTime),
      bottom: logic.showMenu ? 0 : -60,
      left: 0,
      right: 0,
      child: Container(
        height: 60,
        color: logic.isDark ? Colors.black : Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 16),
        child: Column(
          children: [
            26.sizeBoxH,
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                InkWell(
                  onTap: () async => logic.loadOtherEpisode(false, showLoading: true),
                  child: Row(
                    children: [
                      Image.asset('text_last.png'.acgImgPath, width: 20, height: 20),
                      SizedBox(width: 12),
                      Text('上一章',
                          style: TextStyle(
                            fontSize: 14,
                            color: logic.isDark ? Colors.white : Colors.black,
                          )),
                    ],
                  ),
                ),
                InkWell(
                  onTap: () async => logic.loadOtherEpisode(true, showLoading: true),
                  child: Row(
                    children: [
                      Text('下一章',
                          style: TextStyle(
                            fontSize: 14,
                            color: logic.isDark ? Colors.white : Colors.black,
                          )),
                      SizedBox(width: 12),
                      Image.asset('text_next.png'.acgImgPath, width: 20, height: 20),
                    ],
                  ),
                )
              ],
            ),
          ],
        ),
      ),
    );
  }

  _buildEndDrawer() {
    return Container(
      color: logic.isDark ? Colors.black : Colors.white,
      width: 210,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          80.sizeBoxH,
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Text(
              logic.mediaInfo?.title ?? '',
              style: TextStyle(fontSize: 16, color: logic.isDark ? Colors.white : Colors.black, fontWeight: FontWeight.w500),
              overflow: TextOverflow.ellipsis,
            ),
          ),
          18.sizeBoxH,
          Container(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            color: AppColors.actionRed,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '共${logic.mediaInfo?.totalEpisode}话 ${logic.mediaInfo?.getUpdateString ?? ''}',
                  style: TextStyle(fontSize: 14, color: Colors.white, fontWeight: FontWeight.w500),
                ),
                InkWell(
                  onTap: () => logic.onChangeSortAction(),
                  child: Row(
                    children: [
                      Obx(
                        () => Transform.rotate(
                          angle: logic.isAscend.value ? 0 : pi,
                          child: Image.asset('text_play_sort.png'.acgImgPath, width: 20),
                        ),
                      ),
                      SizedBox(width: 4),
                      Obx(
                        () => Text(
                          logic.isAscend.value == true ? '正序' : '倒序',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
          Expanded(
              child: GetBuilder<TextNovelReadLogic>(
            id: 'list',
            builder: (_) => ListView.builder(
              itemCount: _.allEpisodes.length,
              padding: const EdgeInsets.only(top: 6),
              itemBuilder: (context, index) {
                ComicChapterInfo? info = _.allEpisodes[index];
                return GestureDetector(
                  onTap: () {
                    Get.back();
                    logic.loadDataWithIndex(index);
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    height: 40,
                    child: Row(
                      children: [
                        _buildDrawerItem(
                          '${info.episodeNumber ?? 1}. ${info.name} ',
                          _.detailInfo?.id == info.id,
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ))
        ],
      ),
    );
  }

  _buildDrawerItem(String title, bool select) {
    return Expanded(
        child: Text(
      title,
      style: TextStyle(
        fontSize: 16,
        color: select
            ? AppColors.actionRed
            : logic.isDark
                ? Colors.white.withOpacity(.55)
                : Colors.black.withOpacity(.55),
        fontWeight: select ? FontWeight.w500 : FontWeight.w400,
      ),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    ));
  }
}
